<template>
  <div class="layout-container">
    <!-- 主内容区域 - 添加ref用于获取滚动容器 -->
    <div class="main-content" ref="scrollContainer">
      <keep-alive :include="cachedViews">
        <router-view
          :key="$route.fullPath"
          v-if="!$route.meta.noKeepAlive"
        ></router-view>
      </keep-alive>
      <!-- 不缓存的视图 -->
      <router-view
        :key="$route.fullPath"
        v-if="$route.meta.noKeepAlive"
      ></router-view>
    </div>

    <!-- 底部Tabbar -->
    <van-tabbar route class="fixed-tabbar">
      <van-tabbar-item replace icon="notes-o" to="/article">面经</van-tabbar-item>
      <van-tabbar-item replace icon="star-o" to="/collection">收藏</van-tabbar-item>
      <van-tabbar-item replace icon="like-o" to="/like">喜欢</van-tabbar-item>
      <van-tabbar-item replace icon="user-o" to="/setting">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 需要缓存的组件名称数组
      cachedViews: ['MyArticle', 'MyCollection', 'MyLike', 'MySetting'],
      // 保存每个路由的滚动位置
      scrollPositions: {}
    }
  },
  mounted () {
    // 监听滚动事件
    this.$nextTick(() => {
      const container = this.$refs.scrollContainer
      if (container) {
        container.addEventListener('scroll', this.handleScroll, { passive: true })
      }
    })
  },
  beforeDestroy () {
    // 移除事件监听
    const container = this.$refs.scrollContainer
    if (container) {
      container.removeEventListener('scroll', this.handleScroll)
    }
  },
  methods: {
    // 处理滚动事件，保存当前滚动位置
    handleScroll () {
      const container = this.$refs.scrollContainer
      if (container) {
        this.scrollPositions[this.$route.path] = container.scrollTop
      }
    },
    // 恢复滚动位置
    restoreScrollPosition () {
      this.$nextTick(() => {
        const container = this.$refs.scrollContainer
        if (container && this.scrollPositions[this.$route.path]) {
          container.scrollTop = this.scrollPositions[this.$route.path]
        }
      })
    }
  },
  watch: {
    // 监听路由变化，恢复滚动位置
    $route (to, from) {
      // 如果是返回操作，恢复滚动位置
      if (this.cachedViews.includes(to.name)) {
        this.$nextTick(() => {
          this.restoreScrollPosition()
        })
      }
    }
  }
}
</script>

<style scoped>
.layout-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.main-content {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.fixed-tabbar {
  flex-shrink: 0;
  position: relative !important;
  transform: none !important;
}
</style>
